package com.maysham.tripod.service.impl;

import com.maysham.tripod.config.auth.RoleEnum;
import com.maysham.tripod.dao.RoleDao;
import com.maysham.tripod.dao.UserDao;
import com.maysham.tripod.model.Role;
import com.maysham.tripod.model.User;
import com.maysham.tripod.service.UserService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserDao userDao;

    @Resource
    private RoleDao roleDao;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        return userDao.findByUsername(s);
    }

    @Override
    public void createAdminUser(String name, String encode) {
        User user = new User();
        user.setId("admin");
        user.setUsername(name);
        user.setEnabled(true);
        user.setPassword(encode);
        user.setAuthor(user);
        user.setModifier(user);
        user.setCreatedOn(System.currentTimeMillis());
        user.setUpdatedOn(System.currentTimeMillis());
        Role role = new Role();
        role.setName(RoleEnum.ADMIN.name());
        role.setAuthor(user);
        role.setModifier(user);
        role.setCreatedOn(System.currentTimeMillis());
        role.setUpdatedOn(System.currentTimeMillis());
        user.setRoles(Collections.singletonList(role));
        roleDao.save(role);
        userDao.save(user);
    }
}
